<template>
  <div>
    <!-- 看到没，这里为空 -->
    <a-upload
      listType="picture"
      class="upload-list-inline"
      :fileList="[]" 
      :data="{biz:bizPath}"
      :beforeUpload="beforeUpload"
      :multiple="true"
      :action="uploadAction"
      @change="handleChange"
    >
      <a-button><a-icon type="upload"/> 上传图片</a-button>
    </a-upload>
    <draggable @end="end" :options="{animation: 300}" v-model="fileList" style="display: inline-block">
      <template v-for="(data, index) in fileList">
        <div style="float: left;width:150px;height:150px;margin-right: 10px;margin: 0 8px 8px 0;" :key="index">
          <div style="width: 100%;height: 100%;position: relative;padding: 8px;border: 1px solid #d9d9d9;border-radius: 4px;">
            <img style="width: 100%;" :src="data.filePath" preview="index">
          </div>
        </div>
      </template>
    </draggable>
    <!-- <br/>
    <a-row>
      <a-col :span="12">
        <p>拖拽前json数据：</p>
        <textarea rows="25" style="width: 780px">{{ oldDateSource }}</textarea>
      </a-col>
      <a-col :span="12">
        <p>拖拽后json数据：</p>
        <textarea rows="25" style="width: 780px">{{ newDateSource }}</textarea>
      </a-col>
    </a-row> -->
  </div>
</template>

<script>
  import draggable from 'vuedraggable'
  import { getFileAccessHttpUrl } from '@/api/manage'

  const uidGenerator=()=>{
      return '-'+parseInt(Math.random()*10000+1,10);
  }
  const getFileName=(path)=>{
      if(path.lastIndexOf("\\")>=0){
          let reg=new RegExp("\\\\","g");
          path = path.replace(reg,"/");
      }
      return path.substring(path.lastIndexOf("/")+1);
  }
  export default {
    name: 'ImageDragSort',
    components:{
      draggable
    },
    props: {
      /*这个属性用于控制文件上传的业务路径*/
      bizPath:{
          type:String,
          required:false,
          default:"temp"
      },
    },
    data() {
      return {
        description: '图片拖拽排序',
        spinning: false,
        oldDateSource:[],
        newDateSource:[],
        uploadAction:window._CONFIG['domianURL']+"/sys/common/upload",
        fileList: [],
      }
    },
    created(){
      this.oldDateSource = this.fileList;
    },
    methods:{
      end: function (evt) {
        console.log("拖动前的位置"+evt.oldIndex);
        console.log("拖动后的位置"+evt.newIndex);
        this.sureChange()
      },
      sureChange(){
        for(var i=0;i<this.fileList.length;i++){
          this.fileList[i].sort = i;
        }
        this.newDateSource = this.fileList;
      },
      initFileList(paths){
        if(!paths || paths.length==0){
            this.fileList = [];
            return;
        }
        this.picUrl = true;
        let fileList = [];
        let arr = paths.split(",")
        for(var a=0;a<arr.length;a++){
          let url = getFileAccessHttpUrl(arr[a]);
          fileList.push({
            uid: uidGenerator(),
            name: getFileName(arr[a]),
            sort: a,
            status: 'done',
            url: url,
            response:{
              status:"history",
              message:arr[a]
            }
          })
        }
        this.fileList = fileList
      },
      
            beforeUpload: function(file){
                var fileType = file.type;
                if(fileType.indexOf('image')<0){
                    this.$message.warning('请上传图片');
                    return false;
                }
            },
            handleChange(info) {
                this.picUrl = false;
                let fileList = info.fileList
                //update-begin-author:wangshuai date:20201022 for:LOWCOD-969 判断number是否大于0和是否多选，返回选定的元素。
                if(this.number>0 && this.isMultiple){
                    fileList = fileList.slice(-this.number);
                }
                //update-end-author:wangshuai date:20201022 for:LOWCOD-969 判断number是否大于0和是否多选，返回选定的元素。
                if(info.file.status==='done'){
                    if(info.file.response.success){
                        this.picUrl = true;
                        fileList = fileList.map((file) => {
                            if (file.response) {
                                file.url = file.response.message;
                            }
                            return file;
                        });
                    }
                    //this.$message.success(`${info.file.name} 上传成功!`);
                }else if (info.file.status === 'error') {
                    this.$message.error(`${info.file.name} 上传失败.`);
                }else if(info.file.status === 'removed'){
                    this.handleDelete(info.file)
                }
                this.fileList = fileList
                if(info.file.status==='done' || info.file.status === 'removed'){
                    this.handlePathChange()
                }
            },
            handlePathChange(){
                let uploadFiles = this.fileList
                let path = ''
                if(!uploadFiles || uploadFiles.length==0){
                    path = ''
                }
                let arr = [];
                if(!this.isMultiple){
                    arr.push(uploadFiles[uploadFiles.length-1].response.message)
                }else{
                    for(let a=0;a<uploadFiles.length;a++){
                        // update-begin-author:taoyan date:20200819 for:【开源问题z】上传图片组件 LOWCOD-783
                        if(uploadFiles[a].status === 'done' ) {
                            arr.push(uploadFiles[a].response.message)
                        }else{
                            return;
                        }
                        // update-end-author:taoyan date:20200819 for:【开源问题z】上传图片组件 LOWCOD-783
                    }
                }
                if(arr.length>0){
                    path = arr.join(",")
                }
                this.$emit('change', path,this.imgIndex);
            },
            handleDelete(file){
                //如有需要新增 删除逻辑
                console.log(file)
            },
            handleCancel() {
                this.close();
                this.previewVisible = false;
            },
            close () {

            },
    },
    watch:{
      value: {
        handler(val,oldValue) {
          console.log(val)
          if (val instanceof Array) {
            this.initFileList(val.join(','))
          } else {
            this.initFileList(val)
          }
          if(!val || val.length==0){
            this.picUrl = false;
          }
        },
        //立刻执行handler
        immediate: true
      }
    },
    model: {
      prop: 'value',
      event: 'change'
    }
  }
</script>

<style scoped>

</style>